package cn.hzaspt.car.util;

import android.graphics.Bitmap;

/**
 * Created by hdy on 2017/4/7.
 */

public class ImageUtils {
	public static int red_sj = 0, yellow_sj = 0, green_sj = 0, red_wj = 0,
			yellow_wj = 0, green_wj = 0, red_yx = 0, yellow_yx = 0,
			green_yx = 0, red_jx = 0, yellow_jx = 0, green_jx = 0, red_lx = 0,
			yellow_lx = 0, green_lx = 0;

	public static Bitmap ImageCrop(Bitmap bitmap, int num1, int num2,
			boolean isRecycled) {
		if (bitmap == null) {
			return null;
		}
		int w = bitmap.getWidth(); // 寰楀埌鍥剧墖鐨勫锛岄珮
		int h = bitmap.getHeight();
		int retX, retY;
		int nw, nh;
		if (w > h) {
			if (h > w * num2 / num1) {
				nw = w;
				nh = w * num2 / num1;
				retX = 0;
				retY = (h - nh) / 2;
			} else {
				nw = h * num1 / num2;
				nh = h;
				retX = (w - nw) / 2;
				retY = 0;
			}
		} else {
			if (w > h * num2 / num1) {
				nh = h;
				nw = h * num2 / num1;
				retY = 0;
				retX = (w - nw) / 2;
			} else {
				nh = w * num1 / num2;
				nw = w;
				retY = (h - nh) / 2;
				retX = 0;
			}
		}
		Bitmap bmp = Bitmap.createBitmap(bitmap, retX, retY, nw, nh, null,
				false);
		if (isRecycled && bitmap != null && !bitmap.equals(bmp)
				&& !bitmap.isRecycled()) {
			bitmap.recycle();
			bitmap = null;
		}
		return bmp;// Bitmap.createBitmap(bitmap, retX, retY, nw, nh, null,
		// false);
	}

	/**
	 * 
	 * @param bitmap
	 *            鍘熷浘
	 * @param edgeLength
	 *            甯屾湜寰楀埌鐨勬鏂瑰舰閮ㄥ垎鐨勮竟闀�
	 * @return 缂╂斁鎴彇姝ｄ腑閮ㄥ垎鍚庣殑浣嶅浘銆�
	 */
	public static Bitmap centerSquareScaleBitmap(Bitmap bitmap, int edgeLength) {
		if (null == bitmap || edgeLength <= 0) {
			return null;
		}

		Bitmap result = bitmap;
		int widthOrg = bitmap.getWidth();
		int heightOrg = bitmap.getHeight();

		if (widthOrg > edgeLength && heightOrg > edgeLength) {
			// 鍘嬬缉鍒颁竴涓渶灏忛暱搴︽槸edgeLength鐨刡itmap
			int longerEdge = (int) (edgeLength * Math.max(widthOrg, heightOrg) / Math
					.min(widthOrg, heightOrg));
			int scaledWidth = widthOrg > heightOrg ? longerEdge : edgeLength;
			int scaledHeight = widthOrg > heightOrg ? edgeLength : longerEdge;
			Bitmap scaledBitmap;

			try {
				scaledBitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth,
						scaledHeight, true);
			} catch (Exception e) {
				return null;
			}

			// 浠庡浘涓埅鍙栨涓棿鐨勬鏂瑰舰閮ㄥ垎銆�
			int xTopLeft = (scaledWidth - edgeLength) / 2;
			int yTopLeft = (scaledHeight - edgeLength) / 2;

			try {
				result = Bitmap.createBitmap(scaledBitmap, xTopLeft, yTopLeft,
						edgeLength, edgeLength);
				scaledBitmap.recycle();
			} catch (Exception e) {
				return null;
			}
		}

		return result;
	}
}
